package com.fc.v2.util;

import com.fc.v2.model.auto.ApplyParticipator;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import com.spire.doc.documents.ImageType;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


public class ECertUtils {
    /**
     * 生成证书
     * @param qyName
     * @param areaName
     * @throws IOException
     */
    public static Map<String,Object> generateECert(HttpServletRequest request, HttpServletResponse response
                                , String proName, String proveNum, String manName, String rank,String participatorBuilder) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
//        calendar.add(Calendar.YEAR, 1);
//        String nextYear = calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月";
////        String qyName = "测试信息科技有限公司";
////        String areaName = "德城区";
//        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy年MM月");
//        //request.getSession().getServletContext().getRealPath("")获取当前路径，
        //此获取得到是获取证书模板文件路径
        String courseFile= "C:\\_Publish\\社科联\\证书模板\\";
        //加载文件   "C:\_Publish\社科联\证书模板\certificate.docx"
        Document doc = new Document(courseFile+"certificate.docx");

        //定位书签
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        //项目名称书签
        bookmarkNavigator.moveToBookmark("proName");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(proName,true);
        //项目批准号书签
        bookmarkNavigator.moveToBookmark("proveNum");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent("123456",true);
        //负责人书签
        bookmarkNavigator.moveToBookmark("manName");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(manName,true);
        if(rank.equals("a")){
            rank = "优秀";
        }else if(rank.equals("b")){
            rank = "良好";
        }else if(rank.equals("c")){
            rank = "合格";
        }else if(rank.equals("d")){
            rank = "不合格";
        }
        //鉴定等级书签
        bookmarkNavigator.moveToBookmark("rank");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(rank,true);
        //年书签
        bookmarkNavigator.moveToBookmark("year");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(String.valueOf(year),true);
        //月书签
        bookmarkNavigator.moveToBookmark("month");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(String.valueOf(month),true);
        //日书签
        bookmarkNavigator.moveToBookmark("day");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(String.valueOf(day),true);
        //成员书签
        bookmarkNavigator.moveToBookmark("partName");
        //用新的内容替换原书签内容
        bookmarkNavigator.replaceBookmarkContent(participatorBuilder,true);

        //保存docx文件
//        doc.saveToFile("D:\\zyxxgl\\dzzs\\new_certificate.docx", FileFormat.Docx);
        //将指定页保存为BufferedImage
        BufferedImage image= doc.saveToImages(0, ImageType.Bitmap);
        Map<String,Object> resultMap = new HashMap<>();
        String result = "0";
        //将图片数据保存为PNG格式文档
        File file= new File("C:\\_Publish\\社科联\\生成证书\\"+proName+year+month+day+".png");
        try {
            ImageIO.write(image, "PNG", file);
            result = "1";
            resultMap.put("fileUrl","C:\\_Publish\\社科联\\生成证书\\"+proName+year+month+day+".png");
            resultMap.put("fileName",proName+year+month+day+".png");
//            responseFileStream(response,"C:\\_Publish\\社科联\\生成证书\\"+proName+year+month+day+".png",
//                    proName+year+month+day+".png","png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultMap.put("result",result);
        return resultMap;
    }

    /**
     * 响应体加入文件流
     * @param response
     * @param filePath	文件从盘符开始的完整路径
     */
    private static void responseFileStream(HttpServletResponse response, String filePath,String fileName
            ,String fileType){
        System.err.println("responseFileStream imgPath:"+filePath);
        if(filePath.contains("%")){
            try {
                filePath = URLDecoder.decode(filePath,"UTF-8");
                fileName = URLDecoder.decode(fileName,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("responseFileStream decode error:"+e.toString());
            }
        }
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
            String[] dir = filePath.split("/");
            // String fileName = dir[dir.length-1];
            //String[] array = fileName.split("[.]");
            //String fileType = array[array.length-1].toLowerCase();
            //设置文件ContentType类型
            if("jpg,jepg,gif,png".contains(fileType)){
                //图片类型
                response.setContentType("image/"+fileType);
            }else if("pdf".contains(fileType)){
                //pdf类型
                response.setContentType("application/pdf");
            }else{
                //自动判断下载文件类型
                response.setContentType("multipart/form-data");
            }
            //System.err.println("fileName: "+fileName);
            //设置文件头：最后一个参数是设置下载文件名
            //new String() 解决中文文件名在浏览器显示___，
            response.setHeader("Content-Disposition", "attachment;fileName="+new String(fileName.getBytes("utf-8"),"ISO8859-1"));
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            System.err.println("responseFileStream error:FileNotFoundException" + e.toString());
        } catch (Exception e) {
            System.err.println("responseFileStream error:" + e.toString());
        } finally {
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {
                System.err.println("responseFileStream stream close() error:NullPointerException" + e.toString());
            } catch (Exception e) {
                System.err.println("responseFileStream stream close() error:" + e.toString());
            }
        }
    }

//    public static void main(String[] args) throws IOException {
//        Date date = new Date();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        int nd = calendar.get(Calendar.YEAR);
//        calendar.add(Calendar.YEAR, 1);
//        String nextYear = calendar.get(Calendar.YEAR)+"年"
//                +(calendar.get(Calendar.MONTH)+1)+"月";
//
//        String qyName = "测试信息科技有限公司";
//        String areaName = "德城区";
//        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy年MM月");
//        //加载文件
//        Document doc = new Document("D:\\zyxxgl\\dzzs\\certificate.docx");
//        //定位书签
//        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
//        bookmarkNavigator.moveToBookmark("proName");
//        //用新的内容替换原书签内容
//        bookmarkNavigator.replaceBookmarkContent("神经网络",true);
//        bookmarkNavigator.moveToBookmark("proveNum");
//        //用新的内容替换原书签内容
//        bookmarkNavigator.replaceBookmarkContent("123456",true);
//
//        //保存docx文件
//        //doc.saveToFile("D:\\zyxxgl\\dzzs\\"+nd+"-"+qyName+".docx", FileFormat.Docx);
//        //将指定页保存为BufferedImage
//        BufferedImage image= doc.saveToImages(0, ImageType.Bitmap);
//
//        //将图片数据保存为PNG格式文档
//        File file= new File("D:\\zyxxgl\\dzzs\\"+"certificate.png");
//        ImageIO.write(image, "PNG", file);
//    }

}
